﻿Public Class frmDeudaArrastre
    Dim vectorBlock(16, 2) As String
    Dim vectorDepartamento(16, 5) As String
    Private Sub frmDeudaArrastre_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        vectorBlock = modListadoBlock()
        For i = 0 To vectorBlock.GetLength(0) - 1
            If Trim(vectorBlock(i, 1)) <> "" Then
                cbBlock.Items.Add(vectorBlock(i, 1))
            End If
        Next
        dtpVencimiento.Value = DateAdd(DateInterval.Month, 1, Now)
    End Sub

    Private Sub cbBlock_SelectedIndexChanged(sender As Object, e As EventArgs)
        vectorDepartamento = modListadoDepartamento(CInt(cbBlock.Text))
        For i = 0 To vectorDepartamento.GetLength(0) - 1
            If Trim(vectorDepartamento(i, 1)) <> "" Then
                cbDepartamento.Items.Add(vectorDepartamento(i, 2) & " EX " & vectorDepartamento(i, 3))
            End If

        Next
    End Sub

   
    Private Sub txtDeuda_Leave(sender As Object, e As EventArgs)
        If CInt(txtDeuda.Text) > 0 Then
            btnCalcular.Enabled = True
        Else
            btnCalcular.Enabled = False
        End If
    End Sub

    Private Sub btnCalcular_Click(sender As Object, e As EventArgs)
        Dim valor As Double
        Dim valorCuota, cuotas, resto, i As Integer
        Dim fecha As Date
        dgvDeudaArrastreCuotas.Rows.Clear()
    
    
        With dgvDeudaArrastreCuotas
            .DefaultCellStyle.Font = New Font("Verdana", 10)
            .AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.DisplayedCells
            .AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.DisplayedCells
            .ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
            .AlternatingRowsDefaultCellStyle.BackColor = Color.AntiqueWhite
        End With

        valor = CDbl(txtDeuda.Text)
        cuotas = nudCuotas.Value
        valorCuota = CInt((valor \ cuotas))
        resto = valor Mod cuotas
        fecha = dtpVencimiento.Value
        For i = 0 To cuotas - 1
            dgvDeudaArrastreCuotas.Rows.Add()
            If i > 0 Then
                fecha = DateAdd(DateInterval.Month, 1, fecha)
            End If
            dgvDeudaArrastreCuotas.Rows(i).Cells(0).Value = fecha.ToString("dd/MM/yyyy")
            If i = cuotas - 1 Then
                valorCuota = valorCuota + resto
            End If
            dgvDeudaArrastreCuotas.Rows(i).Cells(1).Value = valorCuota
        Next


    End Sub

    Private Sub btnGrabar_Click(sender As Object, e As EventArgs) Handles btnGrabar.Click
        Dim resultado As DialogResult
        Dim idDepa, i, fa, lastInsertId As Integer
        Dim periodo As String
        Dim ok As Boolean

        resultado = MessageBox.Show("Al guardar se reemplazará esta repactación por cualquier otra precedente. ¿Desea continuar?", "Advertencia", MessageBoxButtons.YesNo)
        If resultado = Windows.Forms.DialogResult.Yes Then
            'RETORNA EL ID DEL DEPARTAMENTO SELECCIONADO
            For i = 0 To vectorDepartamento.GetLength(0) - 1
                If vectorDepartamento(i, 2) = cbDepartamento.Text.Substring(0, 2) Then
                    idDepa = vectorDepartamento(i, 0)
                    Exit For
                End If
            Next
            If idDepa <= 0 Then
                MessageBox.Show("Error en Departamento: No encontrado.")
            Else
                conectar()
                ' INSERTA DATOS DE DEUDA DE ARRASTRE
                cmd.Connection = con
                cmd.CommandText = "INSERT INTO `tdeudaarrastre` (`Valor`, `NumCuotas`, `IDDepartamento`) VALUES ( " & txtDeuda.Text & ", " & nudCuotas.Text & ", " & idDepa.ToString + ");"
                cmd.CommandType = CommandType.Text

                fa = cmd.ExecuteNonQuery
                desconectar()
                If fa > 0 Then
                    ' EXTRAER ID Ingresado
                    conectar()
                    cmd.Connection = con
                    cmd.CommandText = "SELECT MAX(ID) FROM tDeudaArrastre"
                    cmd.CommandType = CommandType.Text
                    dr = cmd.ExecuteReader
                    If dr.HasRows Then
                        dr.Read()
                        lastInsertId = dr(0)
                    End If
                    dr.Close()
                    desconectar()
                    'SI EL ID ES > 0 ENTONCES CONTINUAR INGRESANDO EL DETALLE
                    If lastInsertId > 0 Then
                        If dgvDeudaArrastreCuotas.RowCount > 0 Then
                            For i = 0 To dgvDeudaArrastreCuotas.RowCount - 1
                                ok = True
                                Dim valorCuota As Integer
                                conectar()
                                cmd.Connection = con
                                valorCuota = dgvDeudaArrastreCuotas.Rows(i).Cells(1).Value
                                periodo = dgvDeudaArrastreCuotas.Rows(i).Cells(0).Value
                                cmd.CommandType = CommandType.Text
                                cmd.CommandText = "INSERT INTO `tdeudacuotas` ( `NumCuota`, `FechaVencimiento`, `Valor`, `IDDeudaArrastre`)"
                                cmd.CommandText += " VALUES ( " + (i + 1).ToString + ", '" + periodo + "'," + valorCuota.ToString + "," + lastInsertId.ToString + ");"
                                fa = cmd.ExecuteNonQuery
                                If fa <= 0 Then
                                    ok = False
                                    MessageBox.Show("Error al ingresar cuota para periodo " + periodo)
                                End If
                                desconectar()
                            Next
                            If ok Then
                                MessageBox.Show("Se ha repactado la deuda de arrastre.")
                            End If
                        End If
                    End If
                End If
            End If
        End If
    End Sub

 
End Class